// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  // 1.首次登录检查数据库是否有存储过用户openid
  if(event.tag === 'selectUserInfo'){
    return await db.collection('user').where({
      _openid: wxContext.OPENID
    }).get()
    .then(res => {
      return res.data
    })
  }
  // 2.注册用户
  if(event.tag === 'zhuce'){
    console.log(event,"打印event")
    return await db.collection('user').add({
      data: {
        nickName:event.userInfo.nickName,
        avatarUrl:event.userInfo.avatarUrl,
        createTime: db.serverDate(),
        _openid: wxContext.OPENID,
        done: true
      }
    }) 
    .then(res => {
      return res.data
    })
  }
  // 2.注册用户
  if(event.tag === 'addJinbi'){
    return await db.collection('user').add({
      data: {
        nickName:event.userInfo.nickName,
        avatarUrl:event.userInfo.avatarUrl,
        createTime: db.serverDate(),
        _openid: wxContext.OPENID,
        done: true
      }
    })
    .then(res => {
      return res.data
    })
  }


  // return {
  //   event,
  //   openid: wxContext.OPENID,
  //   appid: wxContext.APPID,
  //   unionid: wxContext.UNIONID,
  // }
}